/*
 * Simple program to interact with a character device "/dev/hello"
 * Supports reading from and writing to the device
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]){
    // Check for minimum required arguments
    if(argc < 2){
        printf("Usage:%s <-r(read)/-w(write)> <string>\n", argv[0]);
        return -1;
    }

    // Open the device file with read/write permissions
    int fd = open("/dev/hello", O_RDWR);
    if(fd == -1)
    {
        perror("open");
        return -1;
    }

    char buf[1024];  // Buffer for read operations
    int len;        // Length variable for read/write operations

    // Handle read operation
    if(strcmp(argv[1], "-r") == 0){
        len = read(fd, buf, 1024);
        if(len < 0){
            perror("read");
            close(fd);
            return -1;
        }
        buf[1023] = '\0';  // Ensure null termination
        printf("read %d bytes from device hello:%s\n", len, buf);
    }

    // Handle write operation
    if(strcmp(argv[1], "-w") == 0){
        if(argv[2] == NULL){
            printf("nothing to write\n");
            close(fd);
            return -1;
        }

        // Calculate write length (including null terminator)
        len = strlen(argv[2]) + 1;
        len = len < 1024 ?  len : 1024;  // Cap at buffer size
        len = write(fd, argv[2], len);
        if(len < 0 ){
            perror("write");
            close(fd);
            return -1;
        } 
        printf("write %d bytes to device hello\n", len);
    }

    close(fd);  // Clean up file descriptor
    return 0;
}